package web.sms.mvc.controller.test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import web.sms.mvc.service.WechatService;
import web.sms.utils.URLConnectionHelper;

import java.io.UnsupportedEncodingException;


/**
 * 时间： 2017/12/11
 *
 * @author Eoly
 */
@Controller
@RequestMapping("")
public class PageTestController {

    private final WechatService wechatService;

    @Autowired
    public PageTestController(WechatService wechatService) {
        this.wechatService = wechatService;
    }

    @RequestMapping(value = "/wechat/test.html", method = RequestMethod.GET)
    public String test(
            @RequestParam
                    String code,
            Model model
    ) {
        //得到 code
        String APPID = "wx5f7c67aed1e686ea";
        String SECRET = "6194fcf6437d2fd1f833938f8977ffdc";
        //获取 openid
        String URL = "https://api.weixin.qq.com/sns/oauth2/access_token";
        String param = "appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code"
                .replace("APPID", APPID).replace("SECRET", SECRET).replace("CODE", code);
        //URLConnectionHelper是一个模拟发送http请求的类
        String jsonStr = URLConnectionHelper.sendGet(URL, param);
        JSONObject jsonObj = JSON.parseObject(jsonStr);
        String openid = jsonObj.get("openid").toString();
        // 获取 access_token
        String token = wechatService.getAccessToken(false);
        //有了用户的openid就可以的到用户的信息了
        String info = URLConnectionHelper.sendGet(
                "https://api.weixin.qq.com/cgi-bin/user/info",
                "access_token={1}&openid={2}".replace("{1}", token).replace("{2}", openid));
        try {
            info = new String(info.getBytes(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //得到用户信息之后返回到一个页面
        model.addAttribute("userInfo", JSON.parseObject(info));
        return "test";
    }
}
